<?php 
require_once("dao/Dao.php");
require_once("dao/ClientDao.php");
require_once("dao/CommandeDao.php");

$requete_supp = $bdd->prepare("DELETE  FROM `admin_facture` WHERE type = 'mobile'");
$requete_supp->execute() or exit(print_r($bdd->errorInfo()));

//$requete = $bdd->prepare(" SELECT * FROM fiche_client WHERE code_client_hto=4"); 
$requete = $bdd->prepare(" SELECT * FROM fiche_client ");
$requete->execute();
$infoclient=$requete->fetchall(PDO::FETCH_ASSOC);
$requete->closeCursor();

class DateTimeFrance extends DateTime {
    public function format($format) {
        $english = array('January', 'February', 'March', 'April', 'May', 'June', 'July','August','September','October','November','December');
        $france = array('Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet','Août','Septembre','Octobre','Novembre','Décembre');
        return str_replace($english, $france, parent::format($format));
    }
}

function format_time($t,$f=':') // t = seconds, f = separator 
{
  return sprintf("%02d%s%02d%s%02d", floor($t/3600), $f, ($t/60)%60, $f, $t%60);
}

// récupération du pied de page 
$myFile = "facture.txt";
$fh = fopen($myFile, 'r');
$contenu = fread($fh, filesize($myFile));
fclose($fh);
 
//chargement de la facturation mobile
$requete = $bdd->prepare(" SELECT * FROM mobile_tarification");
$requete->execute();
$x=0;
while( $tarification = $requete->fetch(PDO::FETCH_OBJ) )
	{
		 $tab_tarification[$tarification->id]['tarif_1'] = $tarification->prix_1;
		 $tab_tarification[$tarification->id]['tarif_2'] = $tarification->prix_2;
		 $tab_tarification[$tarification->id]['tarif_3'] = $tarification->prix_3;
		 $tab_tarification[$tarification->id]['tarif_4'] = $tarification->prix_4;
		 $tab_tarification[$tarification->id]['tarif_5'] = $tarification->prix_5;
		 
		 //pour l'international
		 $tab_tarification[$tarification->code_FT][$tarification->zone_origine][$tarification->zone_destination]['tarif_1'] = $tarification->prix_1;
		 $tab_tarification[$tarification->code_FT][$tarification->zone_origine][$tarification->zone_destination]['tarif_2'] = $tarification->prix_2;
		 $tab_tarification[$tarification->code_FT][$tarification->zone_origine][$tarification->zone_destination]['tarif_3'] = $tarification->prix_3;
		 $tab_tarification[$tarification->code_FT][$tarification->zone_origine][$tarification->zone_destination]['tarif_4'] = $tarification->prix_4;
		 $tab_tarification[$tarification->code_FT][$tarification->zone_origine][$tarification->zone_destination]['tarif_5'] = $tarification->prix_5;
	}

//traitement client par client	
foreach($infoclient as $cle => $donneesclients)
{
	//détail client avec une date de souscription
	$premier_jour_mois_en_cours = date("Y-m-d H:i:s",strtotime('first day of this month'));
	$requete = $bdd->prepare(" SELECT * FROM `detail_client`
								WHERE code_client_hto = ".$donneesclients['code_client_hto']." 
								AND ligne_statut <> 'Terminated' 
								AND date_souscription <>'' 
								AND STR_TO_DATE(date_souscription,'%d/%m/%Y')  < '".$premier_jour_mois_en_cours."'
								AND type_offre = 'mobile' ");
	$requete->execute();
	$detail_client=$requete->fetchall(PDO::FETCH_ASSOC);
	$requete->closeCursor();
	
	$tab_mobile=array();
	$tab_forfait=array();
	$tab_option=array();
	$totaldonnees = array();
	$total_forfait_options=array();
	$total_options=array();
	$total_forfait_plein=array();
	$tab_option_plein=0;
	$facture_messagerie=0;
	$facture = array();
	$facture_total_forfait = 0;
	$facture_total_option = 0;
	$facture_total_mobile = 0;
	$facture_forfait_plein = 0;
	$facture_total_hors_forfait = 0;
	$facture_HF = array();
	$tab_facture_total_HF = array();
	$factureglobal=0;
	$temps_conso=0;
	$horsforfait=0;
	$detail_facture=array('type'=>'0','destinataire'=>'0','heure'=>'0','duree'=>'0',);
	$forfaitactif=array();
	$numerofm=array(1,2,3,4,5,6,7,9);
	$numerof=array(1,2,3,4,5,9);
	$numerom=array(6,7);
	$presentation=array();
	$tab_type_appel=array('MOCN'=>'Appels','MOCNINT'=>'AppelsI','MOCNxO'=>'Appels','MFCN'=>'Appels','MOCNS'=>'Numéros spéciaux','MOCI'=>'Appels à l\'international','MOSN'=>'SMS','MOSNS'=>'SMS premium','MTSNS'=>'SMS premium recu','MOSI'=>'SMS international','MOMN'=>'MMS','MOMI'=>'MMS international','ROC'=>'Appel Roaming','ROS'=>'SMS Roaming','RTC'=>'Appel recu Roaming','RFC'=>'Appel transferé en roaming','ROM'=>'MMS Roaming','VSNV'=>'Messagerie');
	$mois_precedent=date("Y-m-j H:i:s", strtotime('23:59 last day of last month')); 	//mois précédent
	$mois_suivant=date("Y-m-j H:i:s", mktime(0, 0, 0, date("m")+1,1, date("Y")));	//mois suivant
	
	if ($detail_client <> null) 
	{	
		// informations
		$code_client = $donneesclients['code_client_hto'];
		$id_client = $donneesclients['id'];
		$reduction_client = $donneesclients['mobile'] = 0;
		$grille_tarifaire = $donneesclients['grille_tarifaire'] = 'tarif_1';
		$totaldonnees = array();
		$facture_total_HF=0;
	
		$l=0;
		foreach($detail_client as $Ligneclient=>$forfait)
		{
			require "./inc/facture/mobile_calcul_base.php";
			require "./inc/facture/mobile_calcul_consos.php";
		}

/**
 * Logiciel : exemple d'utilisation de HTML2PDF
 * 
 * Convertisseur HTML => PDF, utilise fpdf de Olivier PLATHEY 
 * Distribue sous la licence GPL. 
 *
 * @author		Laurent MINGUET <webmaster@spipu.net>
 */
 	ob_start();
	
	?>
<page style="font-size: 12px" backtop="30mm" backbottom="30mm" backleft="15mm" >
	
	<page_header>
	<div style="position: absolute; left: 50px"> 
    	<img src="./logo-facture/hto.png" >
    	</div>
	</page_header>
    
        <div style="position: absolute; left: 400px; top: 10px; font-size: 14px">
		<?php 
		if ( $donneesclients['raison_social'] == null) 
		{echo $donneesclients['prenom']." ".$donneesclients['nom'];
		$nom = $donneesclients['prenom']." ".$donneesclients['nom'];}
		else	
		{ echo "<br>".$donneesclients['raison_social'];
		$nom = $donneesclients['raison_social'];}
		echo "<br>".$donneesclients['adresse'];
		echo "<br>".$donneesclients['cp']." ".$donneesclients['ville'];
		?>
		</div>
        
    	<div style="position: absolute; left: 0px; top:150px; font-size: 12px">    
        <?php //reference client
		echo 'Référence client: ' .$donneesclients['code_client_hto'];
		echo '<br>Num Facture: m-'.date("Y").date("m").$donneesclients['code_client_hto'];
		echo '<br>Date facturation: '.date("01/m/Y");
		//echo '<br>Date d\'échéance : '.date ("d/m/Y", mktime(0, 0, 0, date("m"),date("d")+30, date("Y")));
		?>
    	</div>
        
        <div style="position: absolute; left: 0px; top:250px; font-size: 12px"> 
        <?php require "./inc/facture/mobile_page_garde.php";?>
        </div>
        
	<page_footer>
    
<?php
	echo $contenu;
?>	

</page_footer> 
</page>
<page style="font-size: 12px" backtop="30mm" backbottom="30mm" backleft="15mm" >
	
	<page_header>
    	<div style="position: absolute; left: 50px"> 
    	<img src="./logo-facture/hto.png" >
    	</div>
	</page_header>
    
        
        <div style="position: absolute; left: 0px; top: 10px; font-size: 12px"> 
        <?php require "./inc/facture/mobile_affiche.php";?>
        </div>
        
	<page_footer>
    
<?php
	echo $contenu;
?>

</page_footer> 
</page>
<?php
	if($donneesclients['facture_detail']!='x')
	{ 
		$mois_precedent_debut = date("Y-m-d", strtotime('00:01 first day of last month')); 	//mois précédent
		$mois_precedent_fin = date("Y-m-d", strtotime('23:59 last day of last month'));		//mois suivant
		foreach($detail_client as $Ligneclient=>$forfait)
		{	
			$numero_ligne = $forfait['ndi'];
			if (strlen($numero_ligne)==10)
			{
				$recherche=substr($numero_ligne,1);}else{$recherche=$numero_ligne;
			}
				if($forfait['facture_detail']!='x')
				{	
					$requete = $bdd->prepare("SELECT * FROM cdr_mobile WHERE Msisdn like \"%".$recherche."\"  "); 			
					$requete->execute();
					$requete->setFetchMode(PDO::FETCH_ASSOC);
					$count = $requete->rowCount();
					if($count>'0')
					{
	?>  
						<page style="font-size: 12px" backtop="30mm" backbottom="30mm" backleft="15mm">
							
							<page_header>
								<div style="position: absolute; left: 50px"> 
								<img src="./logo-facture/hto.png" >
								</div>
							</page_header>
						  
							<div style="position: absolute; left: 0px; top:10px; font-size: 10px">
							<?php require "./inc/facture/detail_facture.php";?>
							</div>
							   
							<page_footer>
	
							<?php echo $contenu; ?>   
		
							</page_footer> 
						</page>
<?php 
					}
				}
	}
}
?> 

<?php
	//$dir="facture/".date("mY");
	$dir="facture_temp/".date("mY");
	$dir2="facture/".date("mY");
	if (!is_dir($dir)) {
    mkdir($dir);         
	}
	if (!is_dir($dir2)) {
    mkdir($dir2);         
	}
	$content = ob_get_clean();
	require_once(dirname(__FILE__).'/../../lib/html2pdf/html2pdf.class.php');
	$pdf = new HTML2PDF('P','A4','fr',true, 'utf-8');
	$pdf->WriteHTML($content, isset($_GET['vuehtml']));
	if(is_dir($dir))  
	{ 
	$pdf->Output($dir."/Mobile-".$donneesclients['code_client_hto']."-".date("mY").".pdf", 'F');
	}  
	else 
	{
	mkdir ($dir);
	$pdf->Output($dir."/Mobile-".$donneesclients['code_client_hto']."-".date("mY").".pdf", 'F');
	}
	}
}

//regroupement des csv
	
//dossier de stockage des csv
$dir    = "facture_temp/csv/".date("mY")."/";

// boucle sur les fichiers
$data = array();
foreach (glob($dir."*_detail.csv") as $file){
	$pos_num_client = strpos(basename($file), '_');
	$num_client = substr(basename($file),0,$pos_num_client);
	$fichier_csv_final = $dir.$num_client."_".date("mY")."_regroup.csv";
	
// lecture et combinaison
$fh = fopen($file, 'r');
if(!$num_client)
{
	$data[$num_client] = fread($fh, filesize($file));
}else{
	$data[$num_client] .= fread($fh, filesize($file));
}
fclose($fh);

// écriture
$fh = fopen($fichier_csv_final, 'w') or die("can't open file");
fwrite($fh, $data[$num_client]);
fclose($fh);
}

//création du csv total
foreach (glob($dir."*_regroup.csv") as $file){
	$pos_num_client = strpos(basename($file), '_');
	$num_client = substr(basename($file),0,$pos_num_client);
	$fichier_csv_final = $dir.date("mY")."_total.csv";
	
// lecture et combinaison
$fh = fopen($file, 'r');
$data_total .= fread($fh, filesize($file));
fclose($fh);

// écriture
$fh = fopen($fichier_csv_final, 'w') or die("can't open file");
fwrite($fh, $data_total);
fclose($fh);
}


redirect("lancement-facture");